﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace NService.Common
{
    [Serializable]
    [XmlRoot("services")]
    public class NServiceList : List<ServiceMeta>
    {
        public NServiceList() : base() { }
        public NServiceList(int capacity) : base(capacity) { }
        public NServiceList(IEnumerable<ServiceMeta> collection) : base(collection) { }

        /// <summary>
        /// 根据服务的名称获取服务元数据
        /// </summary>
        /// <param name="name">服务名称</param>
        /// <returns>服务的元数据</returns>
        public ServiceMeta this[string name]
        {
            get
            {
                return this.First(sm => {
                    return sm.Name.Equals(name, StringComparison.OrdinalIgnoreCase);
                });
            }
        }

        new public NServiceList Add(ServiceMeta meta) {
            if (this.Exists(meta)) {
                throw new Exception("不能添加同名服务。");
            }
            base.Add(meta);
            return this;
        }

        public bool Exists(string name) {
            return this.Find(s => { return s.Name.Equals(name, StringComparison.OrdinalIgnoreCase); }) != null;
        }

        public bool Exists(ServiceMeta meta) {
            return this.Find(s => { return s.Name.Equals(meta.Name, StringComparison.OrdinalIgnoreCase); }) != null;
        }

        public NServiceList Remove(string name) {
            ServiceMeta svc = this.Find(s => { return s.Name.Equals(name, StringComparison.OrdinalIgnoreCase); });
            if (svc != null) {
                this.Remove(svc);
            }
            return this;
        }
    }
}
